<?php


namespace app\unify\controller;


use app\BaseController;
use app\unify\model\Config as ConfigModel;
use app\unify\model\ConfigGroup as ConfigGroupModel;
use think\annotation\route\Validate;
use think\db\Query;
use think\Exception;
use think\facade\Db;
use think\Request;
use app\unify\validate\ConfigGroup as ConfigGroupValidate;


class ConfigGroup extends BaseController
{
    /**
     * 配置分组列表
     *
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        return ConfigGroupModel::field('id,name,title,serial')->order("serial ASC, id ASC")->paginate($this->limit);
    }

    /**
     * 新增配置分组
     *
     * @param \think\Request $request
     * @return string
     */
    #[Validate(ConfigGroupValidate::class, scene: ConfigGroupValidate::SAVE)]
    public function save(Request $request): string
    {
        $params = $request->param();

        ConfigGroupModel::create($params);

        return '操作成功';
    }

    /**
     * 修改配置分组
     * @param \think\Request $request
     * @param int $id
     * @return string
     * @throws \think\Exception
     */
    #[Validate(ConfigGroupValidate::class, scene: ConfigGroupValidate::UPDATE)]
    public function update(Request $request, int $id): string
    {

        $configGroup = ConfigGroupModel::findOrEmpty($id);
        if($configGroup->isEmpty()){
            throw new Exception('未找到该分组');
        }

        $configGroup->save($request->param());

        return '操作成功';
    }

    /**
     * 删除配置分组
     *
     * @param array $ids
     * @return string
     */
    #[Validate(ConfigGroupValidate::class, scene: ConfigGroupValidate::DELETE)]
    public function delete(array $ids): string
    {

        Db::transaction(function() use ($ids) {
            ConfigGroupModel::destroy(function (Query $q) use ($ids) {
                $q->where([
                    [ConfigGroupModel::getPrimaryKey(), 'in', $ids]
                ]);
            });
        });

        return '删除成功';
    }

    /**
     * 修改排序号
     * @param int $id
     * @param int $serial
     * @return string
     */
    #[Validate(ConfigGroupValidate::class, scene: ConfigGroupValidate::UPDATE_SERIAL)]
    public function updateSerial(int $id, int $serial): string
    {
        ConfigGroupModel::where([
            [ConfigGroupModel::getPrimaryKey(), '=', $id]
        ])->update([
            'serial' => $serial
        ]);

        return '操作成功';
    }


}